React HooksのTest
React HooksのTest Code
React v18以降は@testing-library/reactを使う
それ以前の場合はreact-hooks-testing-libraryを使う
renderHook()
#WIP
@testing-library/reactを使うのは良いが、docsのどこを見ればよいのかわからない #??
https://testing-library.com/docs/react-testing-library/api/#renderhook
個別のAPI referrenceはあるが、小さな例とかがない
docsが整備されるまでは(?)、react-hooks-testing-libraryのdocsを読めばいい
docs
1つのtestの中でexpectを何回も実行する感じになるのか
testで囲うごとに、renderがresetされる
https://react-hooks-testing-library.com/usage/basic-hooks
code:ts
test('should increment counter from custom initial value', () => {
const { result } = renderHook(() => useCounter(9000))
act(() => {
result.current.increment()
})
expect(result.current.count).toBe(9001)
})
引数を変えて再renderingさせたいとき
code:ts
test('should reset counter to updated initial value', () => {
const { result, rerender } = renderHook(({ initialValue }) => useCounter(initialValue), {
initialProps: { initialValue: 0 }
})
rerender({ initialValue: 10 })
act(() => {
result.current.reset()
})
expect(result.current.count).toBe(10)
})
code:ts
test('should clean up side effect', () => {
let id = 'first'
const { rerender } = renderHook(() => {
useEffect(() => {
sideEffect.start(id)
return () => {
sideEffect.stop(id) // this id will get the new value when the effect is cleaned up
}
}, id)
})
id = 'second'
rerender()
expect(sideEffect.get('first')).toBe(false)
expect(sideEffect.get('second')).toBe(true)
})
hooks Aが、Hook Bに依存している時に、Bのspyを作ってAをテストしたい
https://qiita.com/bebetaro/items/4b4e2e8cdacddb5aa7bf
https://qiita.com/isy/items/0b40b50fad21a8e6c863
https://the2g.com/post/react-16-8-hooks-and-reacttestutils-act
https://ja.reactjs.org/docs/hooks-faq.html#how-to-test-components-that-use-hooks
https://ksmzn.hatenablog.com/entry/react-hooks-testing-library
https://zenn.dev/bom_shibuya/articles/5c3ae7745c5e94
https://kumaaaaa.com/react-testing/
https://qiita.com/ossan-engineer/items/4757d7457fafd44d2d2f
RenderResult
非同期処理
https://medium.com/@doppelmutzi/testing-of-a-custom-react-hook-for-fetching-data-with-axios-26f012948a8f
waitForNextUpdateとかを使う
renderHookの中にある
Error
Error: Could not auto-detect a React renderer. Are you sure you've installed one of the following
import { renderHook } from '@testing-library/react-hooks/dom';とすれば直る
project内でこの書き方してるところ全てにこの修正を施すと直った
import文に/domを加えるmrsekut.icon
#??
異常系のテストを書きたい